from rest_framework.permissions import IsAdminUser
from rest_framework.response import Response
from rest_framework.views import APIView

from goods.models import GoodsVisitCount
from users.models import User
from datetime import date, timedelta


class UserCountView(APIView):
    """
        用户总量统计
    """
    # 权限指定
    permission_classes = [IsAdminUser]

    def get(self, request):
        # 获取注册用户总数
        count = User.objects.filter(is_staff=False).count()

        return Response({'count':count})

class UserDayCountView(APIView):
    """
        当天用户总量统计
    """
    # 权限指定
    permission_classes = [IsAdminUser]

    def get(self, request):
        # 获取当天日期
        now_date = date.today()
        # 获取当天注册用户总数
        count = User.objects.filter(is_staff=False, date_joined__gte=now_date).count()

        return Response({'count':count})


class UserDayActiveCountView(APIView):
    """
        当天登录用户总量统计
    """
    # 权限指定
    permission_classes = [IsAdminUser]

    def get(self, request):
        # 获取当天日期
        now_date = date.today()
        # 获取当天登录用户总数
        count = User.objects.filter(is_staff=False, last_login__gte=now_date).count()

        return Response({'count':count})

class UserDayOrderCountView(APIView):
    """
        当天下单用户总量统计
    """
    # 权限指定
    permission_classes = [IsAdminUser]

    def get(self, request):
        # 获取当天日期
        now_date = date.today()
        # 获取当天下单用户总数
        users = User.objects.filter(is_staff=False, orders__create_time__gte=now_date)
        # 去重
        user = set(users)
        count = len(user)

        return Response({'count':count})


class UserDayMonthCountView(APIView):
    """
        一个月范围内的每天注册用户总量统计
    """
    # 权限指定
    permission_classes = [IsAdminUser]

    def get(self, request):
        # 获取当天日期
        now_date = date.today()
        # 获取30天之前的日期
        old_date = now_date - timedelta(29)
        # 遍历，从30之前开始遍历查询每天的用户注册量
        users=User.objects.filter(is_staff=True)
        data_list = []
        for i in range(30):
            # 起始日期
            index_date = old_date + timedelta(i)
            # 起始日期的下一天日期
            next_date = old_date + timedelta(i + 1)
            count = User.objects.filter(is_staff=False, date_joined__gte=index_date, date_joined__lt=next_date).count()
            data_list.append({'count': count, 'date': index_date})
        # 返回数量
        return Response(data_list)

class GoodsCountView(APIView):
    """
        商品分类访问量统计
    """
    # 权限指定
    permission_classes = [IsAdminUser]

    def get(self, request):
        # 获取当天日期
        now_date = date.today()
        # 获取商品分类访问量
        goods = GoodsVisitCount.objects.filter(date__gte=now_date)
        data_list=[]
        for good in goods:
            count = good.count
            # 获取关联分类对象的名字
            category = good.category.name
            data_list.append({"count":count,'category':category})
        # 返回数量
        return Response(data_list)